<template>
  <div>
    <!-- <el-button type="primary" @click="goBack">返回</el-button> -->
    <div style="padding-top: 10px; margin-left: 50px">
      <!-- <h3>新增排课</h3> -->
    </div>
    <div>
      <el-form :inline="true" style="display: flex">
        <el-form-item label="家庭组" prop="region">
          <el-select
            v-model="ruleForm.Family"
            :disabled="disabled"
            filterable
            placeholder="请选家庭组"
            style="margin: 2px"
            @change="FamilyChange"
          >
            <el-option
              v-for="item in FamilyOptions"
              :key="item.group_id"
              :label="item.group_name"
              :value="item.group_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="langs.page.customer" prop="region">
          <el-select
            v-model="ruleForm.contacts"
            :disabled="disabled"
            placeholder="请选联系人"
            style="margin: 2px"
            @change="coustChange"
          >
            <el-option
              v-for="item in contactsOptions"
              :key="item.id"
              :label="item.cus_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="langs.page.member" prop="region">
          <el-select
            v-model="ruleForm.user"
            :disabled="disabled"
            placeholder="请选学员姓名"
            style="margin: 2px"
            @change="userChange"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.nick_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程卡" prop="region">
          <el-select
            v-model="ruleForm.goods"
            :disabled="disabled"
            placeholder="请选套餐"
            style="margin: 2px"
            @change="goodsChange"
          >
            <el-option
              v-for="item in goodsOptions"
              :key="item.id"
              :label="
                item.goods_name +
                '( 剩余:' +
                item.card_balance +
                item.unit +
                ')'
              "
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div style="margin-left: 38%; margin-bottom: 15px">
        <el-radio-group v-model="radio" @change="radioChange">
          <el-radio :label="'day'">日排课</el-radio>
          <el-radio :label="'week'">周排课</el-radio>
        </el-radio-group>
      </div>
      <div v-if="radio == 'week'">
        <div>
          <span>开课时间：</span>
          <el-date-picker
            v-model="dataPa.start_at"
            format="yyyy-MM-dd"
            :picker-options="{
              disabledDate(time) {
                // 设置禁用状态，参数为当前日期，要求返回 Boolean
                return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
              },
            }"
            placeholder="选择日期"
            type="date"
            value-format="yyyy-MM-dd"
            @change="satrtChange"
          />
          <span style="margin-left: 15px">日期：</span>
          <el-select
            v-model="wakValue"
            multiple
            placeholder="请选择"
            style="width: 500px"
            @change="addDate"
          >
            <el-option
              v-for="items in wakOptions"
              :key="items.name"
              :label="items.name"
              :value="items.name"
            />
          </el-select>
        </div>
        <el-table
          :cell-style="{ 'vertical-align': 'top' }"
          :data="tableData"
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column label="日期" prop="course_week" />
          <el-table-column label="课程" prop="name">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.goods_name"
                  placeholder="请选商品"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in commodityOptions"
                    :key="items.item_goods_id"
                    :label="items.item_goods_name"
                    :value="items.item_goods_id"
                    @click.native="
                      commodityChange(scope.row, items.item_goods_id, index)
                    "
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="老师" prop="address">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.res_user_name"
                  placeholder="请选员工"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in itemsi.doctorOptions"
                    :key="items.user_id"
                    :label="items.user_name"
                    :value="items.user_id"
                    @click.native="
                      doctorChange(scope.row, items.user_id, index)
                    "
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时间" prop="address">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.course_time"
                  placeholder="请选预约时间段"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in itemsi.time_list"
                    :key="items + 1"
                    :label="items"
                    :value="items"
                    @click.native="itemChange(scope.row, index)"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="排课检测" prop="course_week">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <!-- <el-tooltip
                  content="Top Left 提示文字"
                  effect="dark"
                  placement="top-start"
                >
                  <el-button
                    v-if="itemsi.check == 'success'"
                    plain
                    type="success"
                  >
                    可排课
                  </el-button>
                </el-tooltip>
                <el-tooltip
                  content="Top Left 提示文字"
                  effect="dark"
                  placement="top-start"
                >
                  <el-button v-if="itemsi.check == 'error'" plain type="danger">
                    已有排课
                  </el-button>
                </el-tooltip> -->
                <div style="margin-top: 10px">
                  <!-- <el-tooltip v-if="itemsi.check == 'error'">
                    <el-button plain size="mini" type="danger">
                      已有排课
                    </el-button>
                  </el-tooltip> -->
                  <el-tag v-if="itemsi.check == 'error'" type="danger">
                    已有排课
                  </el-tag>
                  <el-tag v-if="itemsi.check == 'success'" type="success">
                    可排课
                  </el-tag>
                  <!-- <el-tooltip v-if="itemsi.check == 'success'">
                    <el-button plain size="mini" type="success">
                      可排课
                    </el-button>
                  </el-tooltip> -->
                </div>
                <!-- <el-button
                  v-if="itemsi.check == 'success'"
                  plain
                  type="success"
                >
                  可排课
                </el-button>
                <el-button v-if="itemsi.check == 'error'" plain type="danger">
                  已有排课
                </el-button> -->
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" prop="address">
            <template slot-scope="scope">
              <div
                v-for="(itemsi, index) in scope.row.item"
                :key="index"
                style="margin: 2px"
              >
                <el-button
                  type="danger"
                  @click.native="delItemData(index, scope)"
                >
                  删除
                </el-button>
                <el-button
                  v-if="index == 0"
                  type="primary"
                  @click="addsbu(index, scope.row)"
                >
                  添加
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <div>
          <span>日期：</span>
          <el-date-picker
            v-model="classRomDate"
            format="yyyy-MM-dd"
            :picker-options="{
              disabledDate(time) {
                // 设置禁用状态，参数为当前日期，要求返回 Boolean
                return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
              },
            }"
            placeholder="选择一个或多个日期"
            type="dates"
            value-format="yyyy-MM-dd"
            @change="showClassRomDate"
          />
        </div>
        <el-table
          :cell-style="{ 'vertical-align': 'top' }"
          :data="tableData"
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column label="日期" prop="course_week" />
          <el-table-column label="课程" prop="name">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.goods_name"
                  placeholder="请选商品"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in commodityOptions"
                    :key="items.item_goods_id"
                    :label="items.item_goods_name"
                    :value="items.item_goods_id"
                    @click.native="
                      commodityChange(scope.row, items.item_goods_id, index)
                    "
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="老师" prop="address">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.res_user_name"
                  placeholder="请选员工"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in itemsi.doctorOptions"
                    :key="items.user_id"
                    :label="items.user_name"
                    :value="items.user_id"
                    @click.native="
                      doctorChange(scope.row, items.user_id, index)
                    "
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="时间" prop="address">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <el-select
                  v-model="itemsi.course_time"
                  placeholder="请选预约时间段"
                  style="margin: 2px"
                >
                  <el-option
                    v-for="items in itemsi.time_list"
                    :key="items + 1"
                    :label="items"
                    :value="items"
                    @click.native="itemChange(scope.row, index)"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="排课检测" prop="course_week">
            <template slot-scope="scope">
              <div v-for="(itemsi, index) in scope.row.item" :key="index">
                <div v-if="itemsi.check" style="margin-top: 10px">
                  <el-button
                    v-if="itemsi.check == 'success'"
                    plain
                    type="success"
                  >
                    可排课
                  </el-button>
                  <el-button v-if="itemsi.check == 'error'" plain type="danger">
                    已有排课
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="address">
            <template slot-scope="scope">
              <div
                v-for="(itemsi, index) in scope.row.item"
                :key="index"
                style="margin: 2px"
              >
                <el-button
                  type="danger"
                  @click.native="delItemData(index, scope)"
                >
                  删除
                </el-button>
                <el-button
                  v-if="index == 0"
                  type="primary"
                  @click="addsbu(index, scope.row)"
                >
                  添加
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 10px">
        <el-button @click="Submit">保存</el-button>
        <!-- <el-button @click="Submit1">保存1</el-button> -->
      </div>
    </div>
  </div>
</template>

<script>
  import { getDeptLists } from '@/api/addOrganization'
  import { getCusGroup } from '@/api/gustomerGroup'
  import {
    courseAdd,
    getCustomerCard,
    getCourseUser,
    // addReservation,
    courseEdit,
    courseCheck,
  } from '@/api/reservation'
  export default {
    props: {
      modify: {
        type: Object,
        required: true,
      },
    },
    data() {
      return {
        disabled: false,

        ruleForm: {
          // 家庭组
          Family: '',
          // 联系人
          contacts: '',
          // 用户
          user: '',
          // 商品
          goods: '',
        },
        // 推荐人
        FamilyOptions: [],
        goodsOptions: [],
        contactsOptions: [],
        userOptions: [],
        DepartmentOptions: [],
        doctorOptions: [],
        positionOptions: [],
        commodityOptions: [],
        itemDataOptions: [],
        timeSlotOptions: [],
        form: {},
        forms: [{}],

        res_user_id: '',
        goods_id: '',
        customer_card_id: '',
        itemData: [],
        itemDay: [],
        formIs: {},

        paramsData: {},
        // -------------------
        radio: 'week',
        radioIf: 1,
        tableData: [],
        wakValue: '',
        wakOptions: [
          {
            name: '周一',
          },
          {
            name: '周二',
          },
          {
            name: '周三',
          },
          {
            name: '周四',
          },
          {
            name: '周五',
          },
          {
            name: '周六',
          },
          {
            name: '周日',
          },
        ],
        classRomDate: '', // 设置多个预约时间是数组类型
        dataPa: {
          start_at: '',
        },
        langs: JSON.parse(window.localStorage.getItem('lang')),
      }
    },
    mounted() {
      this.init()
      if (this.modify.card_name) {
        this.disabled = true
        this.dataPa.group_id = this.modify.group_id
        this.dataPa.res_customer_id = this.modify.res_customer_id
        this.dataPa.app_customer_id = this.modify.app_customer_id
        this.dataPa.customer_card_id = this.modify.customer_card_id
        this.dataPa.original_type = this.modify.type
        this.ruleForm.goods = this.modify.card_name
        this.ruleForm.Family = this.modify.group_name
        this.ruleForm.contacts = this.modify.cus_name
        this.ruleForm.user = this.modify.nick_name
        this.radio = this.modify.type
        // this.dataPa.start_at = this.modify.start_date

        this.tableData = JSON.parse(JSON.stringify(this.modify.week_data))
        this.tableData.forEach((e) => {
          this.wakValue.push(e.course_week)
          e.item.forEach((j) => {
            j.check = ''
            j.doctorOptions = []
            j.time_list = []
          })
        })
        console.log(this.wakValue)

        const params = {
          app_customer_id: this.modify.app_customer_id,
        }
        getCustomerCard(params).then((j) => {
          this.goodsOptions = j.data
          this.goodsOptions.forEach((j) => {
            if (j.id == this.modify.customer_card_id) {
              this.commodityOptions = j.goods_package
            }
          })
        })
      }

      //
    },
    methods: {
      // 初始化 方法
      init() {
        getCusGroup().then((res) => {
          this.FamilyOptions = res.data
        })
        getDeptLists().then((res) => {
          this.DepartmentOptions = res.data
        })
      },
      // 家庭组
      FamilyChange(e) {
        // this.dataPa = {}
        this.tableData = []
        this.wakValue = ''
        this.classRomDate = ''
        this.goodsOptions = []
        this.userOptions = []
        this.ruleForm.goods = ''
        this.ruleForm.user = ''
        this.dataPa.group_id = e
        // this.dataPa.customer_card_id = e

        this.FamilyOptions.forEach((res) => {
          if (res.group_id == e) {
            this.contactsOptions = res.user
            this.ruleForm.contacts = this.contactsOptions[0].cus_name
            this.dataPa.res_customer_id = this.contactsOptions[0].id
            // this.form.customer_tel = this.contactsOptions[0].tel
            this.userOptions = res.child
          }
        })
      },
      coustChange(e) {
        this.dataPa.res_customer_id = e
      },

      // 用户 ， 学生
      userChange(e) {
        this.ruleForm.goods = ''
        this.tableData = []
        this.wakValue = ''
        this.classRomDate = ''
        this.goodsOptions = []
        this.dataPa.app_customer_id = e
        const params = {
          app_customer_id: e,
        }
        getCustomerCard(params).then((j) => {
          this.goodsOptions = j.data
        })
      },
      // 商品 ， 课程卡
      goodsChange(e) {
        this.tableData = []
        this.wakValue = ''
        this.classRomDate = ''
        this.dataPa.customer_card_id = e
        this.goodsOptions.forEach((j) => {
          if (j.id == e) {
            this.commodityOptions = j.goods_package
          }
        })
      },

      // 选择科室医生 , 老师
      doctorChange(e, id, i) {
        this.tableData.forEach((k) => {
          if (k.course_week == e.course_week) {
            e.item[i].doctorOptions.forEach((k) => {
              if (k.user_id == id) {
                e.item[i].check = ''
                e.item[i].course_time = ''
                e.item[i].time_list = k.time_list
                e.item[i].res_user_id = id
              }
            })
          }
        })
      },
      itemChange(e, i) {
        if (this.radio == 'week') {
          const data = {
            user_id: e.item[i].res_user_id,
            course_time: e.item[i].course_time,
            start_date: this.dataPa.start_at,
            course_week: e.course_week,
            type: this.radio,
          }

          courseCheck(data).then((k) => {
            this.$nextTick(() => {
              e.item[i].check = k.data.status
            })
          })
        } else {
          const data = {
            type: this.radio,
            user_id: e.item[i].res_user_id,
            course_time: e.item[i].course_time,
            start_date: e.course_week,
            course_week: e.course_week,
          }

          courseCheck(data).then((k) => {
            this.$nextTick(() => {
              e.item[i].check = k.data.status
            })
          })
        }
      },
      // 选择商品 ， 课程
      commodityChange(e, id, i) {
        this.tableData.forEach((k) => {
          if (k.course_week == e.course_week) {
            k.item[i].res_user_name = ''
            k.item[i].course_time = ''
            k.item[i].check = ''
          }
        })
        this.commodityOptions.forEach((j) => {
          if (j.item_goods_id == id) {
            this.paramsData.consume_num = j.consume_num
          }
        })
        const params = {
          goods_id: id,
          type: this.radio,
          scheduling_date: e.course_week,
        }

        getCourseUser(params).then((j) => {
          this.tableData.forEach((k) => {
            if (k.course_week == e.course_week) {
              k.item[i].doctorOptions = j.data
              k.item[i].goods_id = id
            }
          })
        })
      },

      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
          })
          .catch(() => {})
      },
      // 返回
      goBack() {
        this.$emit('showMain', 0)
      },
      // _____________________
      // 单选框 事件
      radioChange(e) {
        this.classRomDate = ''
        this.wakValue = ''
        this.tableData = []
        this.form.type = e
        if (e == 'day') {
          this.radioIf = 0
        } else {
          this.radioIf = 1
        }
      },
      // week list
      addDate(e) {
        // console.log(e)
        if (this.dataPa.start_at) {
          this.tableData = []
          e.forEach((i) => {
            this.tableData.push({
              course_week: i,
              item: [
                {
                  check: '',
                  goods_id: '',
                  res_user_id: '',
                  course_time: '',
                  doctorOptions: [],
                  time_list: [],
                },
              ],
            })
          })
        } else {
          this.$message.error('选择开课日期')
        }

        // ----------------
        // if (this.dataPa.start_at) {
        //   const arr = e
        //   for (let i = 0; i < arr.length; i++) {
        //     for (let j = 0; j < this.tableData.length; j++) {
        //       if (arr[i] === this.tableData[j].course_week) {
        //         this.tableData.splice(j, 1)
        //         --j
        //       }
        //     }
        //   }
        //   arr.forEach((i) => {
        //     this.tableData.push({
        //       course_week: i,
        //       item: [
        //         {
        //           check: '',
        //           goods_id: '',
        //           res_user_id: '',
        //           course_time: '',
        //           doctorOptions: [],
        //           time_list: [],
        //         },
        //       ],
        //     })
        //   })
        // } else {
        //   this.$message.error('选择开课日期')
        // }
        // ----------------
      },
      // week 同一天 添加 课程
      addsbu(i, e) {
        this.tableData.forEach((j) => {
          if (e.course_week == j.course_week) {
            j.item.push({
              check: '',
              res_user_id: '',
              goods_id: '',
              course_time: '',
              doctorOptions: [],
              time_list: [],
            })
          }
        })
      },
      // week
      delItemData(i, e) {
        this.tableData.forEach((j) => {
          if (e.row.course_week == j.course_week) {
            if (j.item.length == 1) {
              this.tableData.splice(e.$index, 1)
              if (this.radio == 'week') {
                this.wakValue = []
                this.tableData.forEach((k) => {
                  this.wakValue.push(k.course_week)
                })
                // this.wakValue.forEach((k) => {
                //   if (k == e.row.course_week) {
                //     k = ''
                //   }
                // })
              }
            } else {
              j.item.splice(i, 1)
            }
          }
        })
      },

      // 选择日期 day
      showClassRomDate(e) {
        if (e != null) {
          this.tableData = []
          e.forEach((j) => {
            this.tableData.push({
              course_week: j,
              item: [
                {
                  check: '',
                  goods_id: '',
                  res_user_id: '',
                  course_time: '',
                  doctorOptions: [],
                  time_list: [],
                },
              ],
            })
          })
        }
      },
      satrtChange(e) {
        if (!e) {
          this.tableData = []
          this.wakValue = ''
        } else {
          if (this.wakValue) {
            this.addDate(this.wakValue)
          }
        }
      },
      Submit() {
        const jy = {
          // 家庭组
          Family: '选择家庭组',
          // 联系人
          contacts: '选择联系人',
          // 用户
          user: '选择孩子',
          // 商品
          goods: '选择课程卡',
        }
        if (Object.keys(this.ruleForm).length === 0) {
          this.$message.error('请填写信息')
          return
        } else {
          for (var key in this.ruleForm) {
            if (this.ruleForm[key] == '') {
              this.$message.error(jy[key])
              return
            }
          }
        }

        if (Object.keys(this.tableData).length === 0) {
          this.$message.error('请填写排课信息')
          return
        } else {
          for (let e of this.tableData) {
            for (let item of e.item) {
              for (var keys in item) {
                if (item[keys] == '' || item[keys] == null) {
                  if (
                    keys == 'check' ||
                    keys == 'time_list' ||
                    keys == 'doctorOptions'
                  ) {
                    // console.log(keys)
                  } else {
                    this.$message.error('填写排课信息')
                    return
                  }
                }
              }
            }
          }
        }
        if (this.radio == 'week') {
          if (this.dataPa.start_at == '') {
            this.$message.error('选择开课日期')
            return
          }
        }
        this.tableData.forEach((e) => {
          e.item.forEach((k) => {
            delete k.doctorOptions
            delete k.time_list
            delete k.res_user_name
            delete k.goods_name
            delete k.check
          })
        })
        const week_data = JSON.stringify(this.tableData)
        this.dataPa.week_data = week_data
        this.dataPa.type = this.radio

        if (this.modify.week_data) {
          this.$confirm('此操作将永久删除该调课,排课,请假, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
          })
            .then(() => {
              courseEdit(this.dataPa)
                .then(() => {
                  this.$message({
                    message: '修改排课成功',
                    type: 'success',
                  })
                  this.goBack()
                })
                .catch(() => {
                  this.$message.error('失败')
                  //
                })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作',
              })
            })
        } else {
          courseAdd(this.dataPa).then(() => {
            this.$message({
              message: '排课成功',
              type: 'success',
            })
            this.goBack()
          })
        }
      },
      // 排课校验
      Submit1() {
        console.log(this.modify.week_data)
        console.log(this.tableData)
      },
    },
  }
</script>

<style></style>
